package net.dgg.zz.api.credential.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.*;
import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.user.service.UserManager;
import net.dgg.zz.api.credential.entity.SimpleGeneralCertificate;
import net.dgg.zz.api.credential.service.GeneralCredentialApiService;
import net.dgg.zz.common.entity.PageModel;
import net.dgg.zz.common.service.ProductService;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DataTableResponse;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.credential.excption.CertificateExcption;
import net.dgg.zz.credential.generalCredential.service.GeneralCredentialService;
import net.fblock.log.NLog;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 证书对外接口
 *
 * @author wmj
 * @date 2018/9/4 0004
 */
@Controller
@RequestMapping(value = "/api/zs/credential")
@Api(description = "证书接口")
public class CredentailApiController extends DggBaseController {


    @Resource
    private GeneralCredentialService generalCredentialService;

    @Resource
    private ProductService productService;

    @Resource
    private UserManager userManager;

    @Resource
    private SystemRecordService systemRecordService;

    @Resource
    private GeneralCredentialApiService generalCredentialApiService;

    @Resource
    private TranslateUtil translateUtil;




    /**
     * 修改证书财务信息
     *
     * @return
     */
    @NLog
    @RequestMapping(value = "v1/update_alliance_account_balance.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改证书财务信息", notes = "费用申请通过审核后调用进行证书相关信息修改", httpMethod = "POST")
    public DggRestResponse updateCredentailFinance(@ApiParam(name = "orderId", value = "销售子订单id", required = true) @RequestParam Long orderId,
                                                   @ApiParam(name = "userId", value = "通过审核人的id", required = true) @RequestParam Long userId,
                                                   @ApiParam(name = "deposit", value = "定金(如果选择的是全款，也存在定金里面)", required = false) @RequestParam BigDecimal deposit,
                                                   @ApiParam(name = "depositPayTime", value = "定金支付时间", required = false) @RequestParam String depositPayTime,
                                                   @ApiParam(name = "tailMoney", value = "尾款", required = false) @RequestParam BigDecimal tailMoney,
                                                   @ApiParam(name = "tailMoneyPayTime", value = "尾款支付时间", required = false) @RequestParam String tailMoneyPayTime,
                                                   @ApiParam(name = "accountMoney", value = "打款费用（尾款+定金）", required = true) @RequestParam BigDecimal accountMoney,
                                                   @ApiParam(name = "currentApplyMoney", value = "当次费用申请金额", required = true) @RequestParam BigDecimal currentApplyMoney) {
        try {
             Date depositPayTimes = StringUtils.isNotEmpty(depositPayTime) ? DateUtil.stringToDate(depositPayTime, "yyyy-MM-dd HH:mm:ss") : null;
            Date tailMoneyPayTimes = StringUtils.isNotEmpty(tailMoneyPayTime) ? DateUtil.stringToDate(tailMoneyPayTime, "yyyy-MM-dd HH:mm:ss") : null;
            generalCredentialApiService.updateCredentialFinance(orderId, userId, deposit, depositPayTimes, tailMoney, tailMoneyPayTimes, accountMoney, currentApplyMoney);
            return this.getSuccessResponse("修改成功");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }


    }


    /**
     * 修改销售子订单状态
     *
     * @return
     */
    @NLog
    @RequestMapping(value = "v1/update_product_cost_state.do", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改销售子订单状态", notes = "费用申请点击修改销售子订单状态", httpMethod = "POST")
    public DggRestResponse updateProductCostState(@ApiParam(name = "orderId", value = "销售子订单id", required = true) @RequestParam Long orderId,
                                               @ApiParam(name = "userId", value = "修改人的id", required = true) @RequestParam Long userId,
                                               @ApiParam(name = "type", value = "费用审核状态 1.新增 2.审核不通过", required = true) @RequestParam Integer type) {
        try {
            generalCredentialApiService.updateProductCostState(orderId, userId, type);
            return this.getSuccessResponse("修改成功");
        } catch (CertificateExcption c) {
            c.printStackTrace();
            return this.getFailResponse(c.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }


    }

    @NLog
    @RequestMapping(value = "v1/list.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "分页获取证书列表", notes = "分页获取证书列表", httpMethod = "GET", response = SimpleGeneralCertificate.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "apiKeywords", value = "综合查询关键字（证书编号，持证人，合同号，订单号）"),
            @ApiImplicitParam(name = "keywords", value = "综合查询关键字（签单商务姓名，签单商务ID）"),
            @ApiImplicitParam(name = "signOrgName", value = "事业部"),
            @ApiImplicitParam(name = "page", value = "当前页面", required = true),
            @ApiImplicitParam(name = "limit", value = "页面数", required = true)
    })
    public DggRestResponse list(@RequestParam(value = "apiKeywords", required = false) String apiKeywords,
                                @RequestParam(value = "keywords", required = false) String keywords,
                                @RequestParam(value = "signOrgName", required = false) String signOrgName,
                                @RequestParam("page") Integer page,
                                @RequestParam("limit") Integer limit) {
        try {
            if(page == null || limit == null){
                return this.getFailResponse("分页参数不能为空");
            }
            Map<String, Object> params = new HashMap<>();
            if(StringUtils.isNotEmpty(apiKeywords)){
                params.put("apiKeywords", apiKeywords);
            }
            if(StringUtils.isNotEmpty(keywords)){
                params.put("keywords", keywords);
            }
            if(StringUtils.isNotEmpty(signOrgName)){
                params.put("signOrgName", signOrgName);
            }
            params.put("page", page);
            params.put("limit", limit);

            List<SimpleGeneralCertificate> simpleGeneralCertificates = generalCredentialApiService.listCredential(params);
            // 财务那边的接口好像会自己转换
            // simpleGeneralCertificates = translateUtil.translateList(new String[]{"certificateLevel"}, simpleGeneralCertificates);

            JSONObject result = new JSONObject();
            result.put("page", page);
            result.put("limit", limit);
            result.put("total", params.get("count"));
            result.put("record", simpleGeneralCertificates);
            return this.getSuccessResponse(result);
        } catch (Exception e) {
            e.printStackTrace();
            return this.getFailResponse(e.getMessage());
        }
    }
}
